<?php
class ContactPublishController extends Zone_Action{
	protected function fieldCompany(){
		return array(
			owner_by_id	=> array(
				type			=> 'NONE',
				default_value	=> 0
			),
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),
			date_updated	=> array(
				type			=> 'NONE',
				default_value	=> new Model_Expr('NOW()')
			),
			title => array(
				type => 'CHAR',
				no_empty => true,
				form_label => 'Tên giao dịch'
			),
			email => array(
				type 		=> 'EMAIL',
				form_label  => 'email'
			),
			desc => array(
				type 		=> 'CHAR',
				form_label  => 'Ghi chú'
			),
			phone => array(
				type => 'CHAR',
				form_label => 'Phone'
			),
			fax => array(
				type => 'CHAR',
				form_label => 'Fax'
			),
			address => array(
				type => 'CHAR',
				form_label => 'Địa chỉ'
			),
			address2 => array(
				type => 'CHAR',
				form_label => 'Địa chỉ phụ'
			),
			homepage => array(
				type => 'CHAR',
				form_label => 'Trang web'
			)
		);
	}

	protected function fieldPerson(){
		return array(
			owner_by_id	=> array(
				type			=> 'NONE',
				default_value	=> 0
			),
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),
			date_updated	=> array(
				type			=> 'NONE',
				default_value	=> new Model_Expr('NOW()')
			),
			title => array(
				type => 'CHAR',
				no_empty => true,
				form_label => 'Tên giao dịch'
			),
			job_title => array(
				type => 'CHAR',
				no_empty => true,
				form_label => 'Chức vụ'
			),
			company_id => array(
				type => 'INT',
				form_label => 'Công ty'
			),
			department => array(
				type => 'CHAR',
				form_label => 'Phòng ban'
			),
			email => array(
				type 		=> 'EMAIL',
				form_label  => 'email'
			),
			phone => array(
				type => 'CHAR',
				form_label => 'Phone'
			),
			fax => array(
				type => 'CHAR',
				form_label => 'Fax'
			),
			address => array(
				type => 'CHAR',
				form_label => 'Địa chỉ'
			),
			address2 => array(
				type => 'CHAR',
				form_label => 'Địa chỉ phụ'
			),
			homepage => array(
				type => 'CHAR',
				form_label => 'Trang web'
			)
		);
	}

	/* Company list */
	public function companyAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `contacts_companies` as `a`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`owner_by_id`='0'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`	
			FROM  `contacts_companies` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`owner_by_id`='0'
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Contact/Publish/Company?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
					
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}
	
	public function viewcompanyAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts_companies` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				`a`.`owner_by_id`='0' 
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
		
		$this->set(array(
			post => $post
		));	
	}
		
	public function uploadcompanyAction(){
		$this->removeLayout();		
		$user_id = get_user_id();		
		$post_id = get("ID",0);
				
		$post = $this->Model->fetchRow("SELECT * 
			FROM `contacts_companies` 
			WHERE 
				`ID`='$post_id'
				AND `owner_by_id`='0'");
			
		if( !$post ){
			return $this->setJSON(array(
				alert	=> 'Bản ghi đã bị xóa hoặc không tồn tại'
			));
		}
	
		if( isPost() ){
			loadClass('ZData');
			$f = new ZData();

			$f->addField(array(
				img => array(
					type 		=> 'FILE',
					resize		=> array(110,110),
					path		=> 'files/contact/',
					no_empty	=> true,
					return_name	=> true
				)
			));
			
			$data = $f->getData();		
			
			if( !is_array( $data ) ){
				return $this->setJSON(array(
					alert => $data
				));	
			}
			
			if( $post['img'] && ( $post['img'] != $data['img'] ) ){
				@unlink("files/contact/{$post['img']}");
			}
			
			$this->Model->update('contacts_companies',$data,"`ID`='$post_id'");
			
			return $this->setJSON(array(
				close	=> 'no',
				callback => "(function(){
					var link =baseURL+'/files/contact/{$data['img']}';
					$('#contact_img')
						.htm('<a href=\"'+link+'\" target=\"_blank\"><img src=\"'+link+'\"/></a>'
							+ '<a onclick=\"ajax_load(baseURL+\\'/Contact/Publish/Deleteimgcompany?ID={$post['ID']}\\')\">[Xóa ảnh]</a>'
						)
				})()"
			));	
		}
		
		$this->setJSON(array(
			alert	=> 'Truy cập không được cho phép.'
		));
	}

	public function addcompanyAction(){
		$user_id = get_user_id();		
		if( !isPost() ){
			$post = $this->Model->fetchRow("SELECT * 
				FROM `contacts_companies` 
				WHERE 
					`created_by_id`='$user_id' 
					AND `owner_by_id`='0'
					AND `is_draft`='yes'
				LIMIT 1");

			if( $post ){
				$this->set('ID',$post['ID']);
			}else{
				$this->Model->insert('contacts_companies',array(
					is_draft		=> 'yes',
					created_by_id	=> $user_id,
					owner_by_id		=> 0
				));
				
				$this->set('ID',$this->Model->lastId());
			}		
		}			
		
		if(isPost()){
			$post_id = getInt('ID',0);
			
			if( !$this->Model->fetchRow("SELECT * 
				FROM `contacts_companies` 
				WHERE 
					`created_by_id`='$user_id' 
					AND `owner_by_id`='0'
				LIMIT 1") ){
					
				return $this->setJSON(array(
					alert	=> 'Bản đã bị xóa hoặc ghi không tồn tại'				
				));		
				
			}
			
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldCompany() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}
			
			$data['is_draft']='no';			
			$data['created_by_id'] = get_user_id();
			$data['date_created']  = new Model_Expr('NOW()');
			
			$this->Model->update('contacts_companies',$data,"`ID`='$post_id'");				
			
			$this->setJSON(array(
				redirect =>	'#Contact/Publish/Viewcompany?ID='.$post_id
			));
		}		
	}

	public function editcompanyAction(){
		$user_id = get_user_id();		
		$post_id = getInt('ID',0);
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts_companies` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				`a`.`owner_by_id`='0'				
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");

		if( !$post ){
			return $thí->setJSON(array(
				content	=> 'Bản ghi không tồn tại hoặc đã bị xóa'	
			));
		}		
		
		$this->set('post',$post);
		
		if(isPost()){		
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldCompany() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}			
			
			$this->Model->update('contacts_companies',$data,"`ID`='$post_id'");				
			
			$this->setJSON(array(
				redirect =>	'#Contact/Publish/Viewcompany?ID='.$post_id
			));
		}
	}	

	public function deletecompanyAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts_companies` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				`a`.`owner_by_id`='0' 
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
			
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Bản ghi đã bị xóa hoặc không tồn tại'			
			));
		}
		
		$this->Model->delete('contacts_companies',"`ID`='$post_id'");
		if( $post['img'] ){
			@unlink("files/contact/{$post['img']}");
		}				
		
		return $this->setJSON(array(
			redirect => '#Contact/Publish/Company'
		));		
	}

	public function deleteimgcompanyAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*
			FROM `contacts_companies` as `a`
			WHERE 
				`a`.`owner_by_id`='0' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
			
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Bản ghi đã bị xóa hoặc không tồn tại'			
			));
		}
		
		if( $post['img'] ){
			@unlink("files/contact/{$post['img']}");
		}
		
		$this->Model->update('contacts_companies',array(
			img	=> NULL
		),"ID='$post_id'");	
		
		return $this->setJSON(array(
			callback => "(function(){
				$('#contact_img').htm('')
			})()"
		));	
	}	

	public function deleteallcompanyAction(){
		$ids = get('ID',array(),true);
		$this->removeLayout();
		$user_id = get_user_id();
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts_companies` as `a`
				WHERE 
					`a`.`owner_by_id`='0' 
					AND `a`.`ID`='$post_id'
				LIMIT 1");

			$this->Model->delete('contacts_companies',"`ID`='$id'");
			
			if( $post['img'] ){
				@unlink("files/contact/{$post['img']}");
			}			
		}
	
		return $this->setJSON(array(
			redirect => '#Contact/Publish/Company'
		));
	}	


	
	/* Person list */	
	public function indexAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','email','phone','address','address2');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`		
			FROM  `contacts` as `a`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`owner_by_id`='0'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				`u`.`username` as `created_by_name`,	
				`u`.`is_deleted` as `created_is_deleted`	
			FROM  `contacts` as `a`
			LEFT JOIN `users` as `u`
				ON `a`.`created_by_id`=`u`.`ID`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`owner_by_id`='0'
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Contact/Publish?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
					
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));			
	}

	public function viewpersonAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`,
				`d`.`title` as `company_title`	
			FROM `contacts` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			LEFT JOIN `contacts_companies` as `d`
				ON `a`.`company_id`=`d`.`ID`
			WHERE 
				`a`.`owner_by_id`='0' 
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
		
		$this->set(array(
			post => $post
		));	
	}
		
	public function uploadpersonAction(){
		$this->removeLayout();		
		$user_id = get_user_id();		
		$post_id = get("ID",0);
				
		$post = $this->Model->fetchRow("SELECT * 
			FROM `contacts` 
			WHERE 
				`ID`='$post_id'
				AND `owner_by_id`='0'");
			
		if( !$post ){
			return $this->setJSON(array(
				alert	=> 'Bản ghi đã bị xóa hoặc không tồn tại'
			));
		}

		if( isPost() ){
			loadClass('ZData');
			$f = new ZData();

			$f->addField(array(
				img => array(
					type 		=> 'FILE',
					resize		=> array(110,110),
					path		=> 'files/contact/',
					no_empty	=> true,
					return_name	=> true
				)
			));
			
			$data = $f->getData();		
			
			if( !is_array( $data ) ){
				return $this->setJSON(array(
					alert => $data
				));	
			}
			
			if( $post['img'] && ( $post['img'] != $data['img'] ) ){
				@unlink("files/contact/{$post['img']}");
			}
			
			$this->Model->update('contacts',$data,"`ID`='$post_id'");
			
			return $this->setJSON(array(
				close	=> 'no',
				callback => "(function(){
					var link =baseURL+'/files/contact/{$data['img']}';
					$('#contact_img')
						.htm('<a href=\"'+link+'\" target=\"_blank\"><img src=\"'+link+'\"/></a>'
							+ '<a onclick=\"ajax_load(baseURL+\\'/Contact/Publish/Deleteimgperson?ID={$post['ID']}\\')\">[Xóa ảnh]</a>'
						)
				})()"
			));	
		}
	}

	public function addpersonAction(){
		$user_id = get_user_id();		
		
		$companies = $this->Model->fetchAll("SELECT `a`.* FROM `contacts_companies` as `a` WHERE `a`.`is_draft`='no' AND `a`.`owner_by_id`='0'");
		$this->set('companies',$companies);
		
		if( !isPost() ){
			$post = $this->Model->fetchRow("SELECT * 
				FROM `contacts` 
				WHERE 
					`created_by_id`='$user_id' 
					AND `is_draft`='yes' LIMIT 1");

			if( $post ){
				$this->set('ID',$post['ID']);
			}else{
				$this->Model->insert('contacts',array(
					is_draft		=> 'yes',
					created_by_id	=> $user_id,
					owner_by_id		=> $user_id
				));
				
				$this->set('ID',$this->Model->lastId());
			}		
		}			
		
		if(isPost()){
			$post_id = getInt('ID',0);
			
			if( !$this->Model->fetchRow("SELECT * 
				FROM `contacts` 
				WHERE `created_by_id`='$user_id' LIMIT 1") ){
					
				return $this->setJSON(array(
					alert	=> 'Bản đã bị xóa hoặc ghi không tồn tại'				
				));		
				
			}
			
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldPerson() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}
			
			$data['is_draft']='no';			
			$data['created_by_id'] = get_user_id();
			$data['date_created']  = new Model_Expr('NOW()');
			
			$this->Model->update('contacts',$data,"`ID`='$post_id'");				
			
			$this->setJSON(array(
				redirect =>	'#Contact/Publish/Viewperson?ID='.$post_id
			));
		}		
	}

	public function editpersonAction(){
		$user_id = get_user_id();		
		$post_id = getInt('ID',0);
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				`a`.`owner_by_id`='0'				
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");

		if( !$post ){
			return $thí->setJSON(array(
				content	=> 'Bản ghi không tồn tại hoặc đã bị xóa'	
			));
		}		
		
		$this->set('post',$post);
		
		$companies = $this->Model->fetchAll("SELECT `a`.* FROM `contacts_companies` as `a` WHERE `a`.`is_draft`='no' AND `a`.`owner_by_id`='0'");
		$this->set('companies',$companies);
		
		if(isPost()){		
			loadClass('ZData');
			$form = new ZData();
			$form->addFields( $this->fieldPerson() );
			$data = $form->getData();			
		
			if( !is_array( $data )){
				return $this->setJSON(array(
					message => error($data)
				));			
			}			
			
			$this->Model->update('contacts',$data,"`ID`='$post_id'");				
			
			$this->setJSON(array(
				redirect =>	'#Contact/Publish/Viewperson?ID='.$post_id
			));
		}
	}	

	public function deletepersonAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*,
				`b`.`username` as `updated_by_name`,	
				`b`.`is_deleted` as `updated_is_deleted`,	
				`c`.`username` as `created_by_name`,	
				`c`.`is_deleted` as `created_is_deleted`	
			FROM `contacts` as `a`
			LEFT JOIN `users` as `b`
				ON `a`.`updated_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			WHERE 
				`a`.`owner_by_id`='0' 
				AND `a`.`is_draft`='no' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
			
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Bản ghi đã bị xóa hoặc không tồn tại'			
			));
		}
		
		$this->Model->delete('contacts',"`ID`='$post_id'");
		if( $post['img'] ){
			@unlink("files/contact/{$post['img']}");
		}				
		
		return $this->setJSON(array(
			redirect => '#Contact/Publish'
		));		
	}

	public function deleteimgpersonAction(){
		$post_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT 
				`a`.*
			FROM `contacts` as `a`
			WHERE 
				`a`.`owner_by_id`='0' 
				AND `a`.`ID`='$post_id'
			LIMIT 1");
			
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Bản ghi đã bị xóa hoặc không tồn tại'			
			));
		}
		
		if( $post['img'] ){
			@unlink("files/contact/{$post['img']}");
		}
		$this->Model->update('contacts',array(
			img	=> NULL
		),"ID='$post_id'");	
		
		return $this->setJSON(array(
			callback => "(function(){
				$('#contact_img').htm('')
			})()"
		));	
	}	

	public function deleteallpersonAction(){
		$ids = get('ID',array(),true);
		$this->removeLayout();
		$user_id = get_user_id();
		
		foreach( $ids as $id ){	
			$post = $this->Model->fetchRow("SELECT 
					`a`.*
				FROM `contacts` as `a`
				WHERE 
					`a`.`owner_by_id`='0' 
					AND `a`.`ID`='$post_id'
				LIMIT 1");

			$this->Model->delete('contacts',"`ID`='$id'");
			
			if( $post['img'] ){
				@unlink("files/contact/{$post['img']}");
			}			
		}
	
		return $this->setJSON(array(
			redirect => '#Contact'
		));
	}
	
}	